<template>
  <div class="app-container">
    <div class="page-top app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="商品名称" prop="comboName">
          <el-input
            style="width: 200px"
            maxlength="16"
            v-model.trim="queryParams.comboName"
            placeholder="请输入商品名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="城市标签" prop="cityName">
          <el-select
            v-model="queryParams.cityName"
            @change="handleChange"
            fit-input-width
            placeholder="请选择"
          >
            <el-option
              v-for="item in cityNameOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="点位名称" prop="positionId">
          <el-cascader
            ref="cascaderRef"
            placeholder="请输入"
            :options="positionOptions"
            clearable
            filterable
            :props="{ value: 'id', label: 'name', children: 'children' }"
            v-model="queryParams.positionId"
            @change="handleQuery"
          />
        </el-form-item>
        <el-form-item label="上架日期" prop="time">
          <div>
            <el-date-picker
              prop="time"
              v-model="queryParams.time"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              @change="handleQuery"
            />
          </div>
        </el-form-item>
        <el-form-item label="">
          <div class="btn-group">
            <el-button plain v-hasPermi="['org:goods:export']" @click="handleExport">
              导出数据
            </el-button>

            <el-radio-group v-model="radioValue" @change="handleDateRange" style="flex-shrink: 0">
              <el-radio-button label="当天" />
              <el-radio-button label="最近7天" />
              <el-radio-button label="最近30天" />
            </el-radio-group>

            <el-date-picker
              v-model="state.timeRange"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="dateChange"
              :clearable="false"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </div>
        </el-form-item>
        <el-form-item label="最近售卖日期" prop="latestTime">
          <div>
            <el-date-picker
              prop="time"
              v-model="queryParams.latestTime"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              @change="handleQuery"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-loading="state.loading">
      <div class="charts">
        <div class="bar-chart">
          <BaseEchart :echart-options="barOptions" />
        </div>
      </div>

      <div style="padding: 20px">
        <el-table :data="tableList" style="width: 100%">
          <el-table-column label="商品名称" show-overflow-tooltip align="center" prop="comboName" />
          <el-table-column label="点位" show-overflow-tooltip align="center">
            <template #default="{ row }">
              <div>
                <el-link
                  :underline="false"
                  type="primary"
                  :disabled="!hasPermi(['org:goods:detail'])"
                  @click="handleDetail(row)"
                  >{{ row.positionCount }}</el-link
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="上架日期"
            show-overflow-tooltip
            align="center"
            prop="firstSaleTime"
          />
          <el-table-column
            label="最近售卖日期"
            show-overflow-tooltip
            align="center"
            prop="lastSaleTime"
          />
          <el-table-column label="投放次数" align="center" prop="shelfCount" />
          <el-table-column label="销售(累计)" align="center" prop="totalSaleNum" />
          <el-table-column label="日均销量" align="center" prop="avgSaleNum" />
          <el-table-column label="售卖率" align="center" prop="repurchaseRate">
            <template #default="{ row }"> {{ row.repurchaseRate || '0.00' }}% </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="state.total > 0"
          :total="state.total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <detailList ref="detailListRef"></detailList>
  </div>
</template>

<script setup name="DeviceAnalysis">
import { parseTime } from '@/utils/tools'
import { onMountedOrActivated } from '@/hooks/common'
import useGlobalStore from '@/store/modules/global'
import detailList from './components/detailList.vue'
import { hasPermi } from '@/utils/tools'
import { getGoodsSalesListApi } from '@/api/statistic'
import { getAllPositions } from '@/api/association'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)
const { proxy } = getCurrentInstance()
let firstLoad = true
const radioValue = ref('当天')
const tableList = ref([])
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  cityName: cityNameOptions.value[0],
  positionId: '',
  time: [],
  latestTime: [],
  shelfStartDate: '',
  shelfEndDate: '',
  latestSaleStartDate: '',
  latestSaleEndDate: ''
})
const state = reactive({
  total: 0,
  loading: false,
  timeRange: [
    parseTime(new Date(), '{y}-{m}-{d}') + ' 00:00:00',
    parseTime(new Date(), '{y}-{m}-{d}') + ' 23:59:59'
  ]
})

const queryRef = ref(null)

function handleChange() {
  getPositionOptions()
  handleQuery()
}
// 重置
function resetQuery() {
  queryRef.value.resetFields()
  radioValue.value = '当天'
  handleDateRange('当天')
}
const barOptions = computed(() => {
  return {
    title: {},
    tooltip: { trigger: 'axis' },
    legend: {
      data: ['销量', '投放'],
      bottom: 0,
      icon: 'circle'
    },
    toolbox: {},
    calculable: true,
    dataset: {
      dimensions: ['comboName', 'totalSaleNum', 'shelfTotalSales'],
      source: tableList.value
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        //x轴文字的配置
        show: true,
        interval: 0, //使x轴文字显示全
        formatter: function (name) {
          var str = ''
          var length = name.length
          var limitLen = 5 //一行显示几个字
          var rowNumber = Math.ceil(length / limitLen)
          if (length > limitLen) {
            for (var p = 0; p < rowNumber; p++) {
              var tempStr = ''
              var start = p * limitLen
              var end = start + limitLen
              if (p == rowNumber - 1) {
                tempStr = name.substring(start, length)
              } else {
                tempStr = name.substring(start, end) + '\n'
              }
              str += tempStr
            }
          } else {
            str = name
          }
          return str
        }
      }
    },
    yAxis: {},
    series: [
      {
        name: '销量',
        type: 'bar'
      },
      {
        name: '投放',
        type: 'bar'
      }
    ],
    dataZoom: [
      {
        show: tableList.value?.length > 4, // 为true 滚动条出现
        realtime: true,
        type: 'slider', // 有type这个属性，滚动条在最下面，也可以不行，写y：36，这表示距离顶端36px，一般就是在图上面。
        height: 5, // 表示滚动条的高度，也就是粗细
        start: 0, // 表示默认展示0%～80%这一段。
        end: 80,
        backgroundColor: 'transparent',
        bottom: 35,
        textStyle: {
          color: 'transparent'
        }
      },
      {
        type: 'inside',
        xAxisIndex: [0],
        zoomOnMouseWheel: false, //滚轮不触发缩放
        moveOnMouseMove: true, //鼠标移动触发平移
        moveOnMouseWheel: true //鼠标滚轮触发平移
      }
    ]
  }
})
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

const dateChange = () => {
  radioValue.value = ''
  handleQuery()
}
function handleDateRange(val) {
  const end = parseTime(new Date(), '{y}-{m}-{d}') + ' 23:59:59'
  const start = new Date()
  switch (val) {
    case '最近30天':
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 29)
      state.timeRange = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    case '最近7天':
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
      state.timeRange = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    case '当天':
      state.timeRange = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    default:
      break
  }
  handleQuery()
}

async function getList() {
  state.loading = true
  const [startDate, endDate] = state.timeRange
  queryParams.value.startDate = startDate ? startDate : ''
  queryParams.value.endDate = endDate ? endDate : ''
  const params = {
    ...queryParams.value,
    positionId:
      queryParams.value.positionId && queryParams.value.positionId.length
        ? queryParams.value.positionId[queryParams.value.positionId.length - 1]
        : '',
    shelfStartDate: queryParams.value.time?.length ? queryParams.value.time[0] : '',
    shelfEndDate: queryParams.value.time?.length ? queryParams.value.time[1] : '',
    latestSaleStartDate: queryParams.value.latestTime?.length
      ? queryParams.value.latestTime[0]
      : '',
    latestSaleEndDate: queryParams.value.latestTime?.length ? queryParams.value.latestTime[1] : ''
  }
  delete params.time
  delete params.latestTime
  try {
    const r = await getGoodsSalesListApi(params)
    tableList.value = r?.data?.rows ?? []
    state.total = r?.data?.total ?? 0
  } finally {
    state.loading = false
  }
  firstLoad = false
}

const positionOptions = ref([])
function getPositionOptions() {
  getAllPositions({ cityName: queryParams.value.cityName }).then((res) => {
    const data = res?.data || []
    positionOptions.value = data.map((item) => {
      if (item.children && item.children.length > 0) {
        item.children = item.children.map((item1) => {
          if (item1.children && item1.children.length > 0) {
            item1.children = item1.children.map((item2) => {
              if (!item2.children || item2.children.length === 0) {
                item2.disabled = true
              }
              return item2
            })
          } else {
            item1.disabled = true
          }
          return item1
        })
      } else {
        item.disabled = true
      }
      return item
    })
  })
}

/** 导出按钮操作 */
function handleExport() {
  const params = {
    ...queryParams.value,
    positionId:
      queryParams.value.positionId && queryParams.value.positionId.length
        ? queryParams.value.positionId[queryParams.value.positionId.length - 1]
        : '',
    shelfStartDate: queryParams.value.time?.length ? queryParams.value.time[0] : '',
    shelfEndDate: queryParams.value.time?.length ? queryParams.value.time[1] : '',
    latestSaleStartDate: queryParams.value.latestTime?.length
      ? queryParams.value.latestTime[0]
      : '',
    latestSaleEndDate: queryParams.value.latestTime?.length ? queryParams.value.latestTime[1] : ''
  }
  delete params.time
  delete params.latestTime
  proxy.download(
    'operation/statistics/admin/combo-sales/export',
    params,
    `商品数据${new Date().getTime()}.xlsx`
  )
}

const detailListRef = ref(null)
function handleDetail(row) {
  detailListRef.value.init(row, queryParams.value)
}

/**init +  onActivated*/
onMountedOrActivated(() => {
  handleQuery()
  getPositionOptions()
})
</script>

<style lang="scss" scoped>
.app-container {
  min-width: 960px;
  overflow-x: auto;
}
.page-top {
  .btn-group {
    display: flex;
    align-items: center;
  }
  .el-radio-group {
    margin: 0 10px;
  }
  div {
    margin-right: 15px;
  }
}

.charts {
  display: flex;
  align-items: center;
  justify-content: space-between;
  max-width: 100%;
  .pie-chart {
    flex: 1;
    min-width: 350px;
    height: 400px;
    margin-right: 20px;
  }
  .bar-chart {
    flex: 2;
    height: 500px;
  }
}
.cards {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  .card {
    width: 300px;
    height: 120px;
    text-align: left;
    display: flex;
    flex-direction: column;
    justify-content: center;
    border-radius: 6px;
    border: 1px solid #33333390;
    padding: 0 20px;
    margin-bottom: 20px;
    font-weight: 600;
    .value {
      font-size: 25px;
      font-weight: bold;
      margin-top: 10px;
    }
  }
}
</style>
